package com.mobile.framework.util;

import java.io.StringWriter;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * A Template Engine With Veloity.
 */
public class TemplateEngine {
	private VelocityContext context;

	private String template;

	private String logName;

	private Log log = LogFactory.getLog(getClass().getName());

	private static boolean isInit = false;

	/**
	 * 构造方法
	 * 
	 */
	public TemplateEngine() {
		init();
		context = new VelocityContext();
		template = "";
		logName = "EXP2";
	}

	/**
	 * 构造方法
	 * 
	 * @param logName1
	 *            日志中显示的名称
	 */
	public TemplateEngine(String logName1) {
		init();
		context = new VelocityContext();
		template = "";
		logName = logName1;
	}

	/**
	 * 初始化
	 * 
	 */
	public void init() {
		if (isInit) {
			// 初始化过了，不用再初始化了
			return;
		}
		try {

			Properties p = new Properties();
			p.setProperty("runtime.log", Config.getProperty("velocity.log"));
			p.setProperty("runtime.log.invalid.references", Config.getProperty(
					"velocity.log.invalid.references", "false"));
			p.setProperty("input.encoding", "UTF-8");
			p.setProperty("output.encoding", "UTF-8");
			Velocity.init(p);
			log.debug("Velocity.init success");
		} catch (Exception e) {
			log.error("Problem initializing Velocity : " + e, e);
		}
		isInit = true;
	}

	/**
	 * 设置模板
	 * 
	 * @param template1
	 */
	public void setTemplate(String template1) {
		template = template1;
	}

	/**
	 * 设置模板变量的值
	 * 
	 * @param name
	 * @param data
	 */
	public void putData(String name, Object data) {
		context.put(name, data);
	}

	/**
	 * 取得模板与数据合并后的结果
	 * 
	 * @return 处理后的结果
	 */
	public String getMergeResult() {

		StringWriter result = new StringWriter();
		try {
			Velocity.evaluate(context, result, logName, template);
		} catch (Exception e) {
			log.error("getMergeResult error,template is: " + template
					+ ",error is:" + e, e);
		}
		return result.toString();
	}
}
